<template>
  <el-form :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon
    label-position="left">
    <el-form-item label="床次" prop="name" style="width: 400px">
      <el-input v-model="ruleForm.name" />
    </el-form-item>

    <el-form-item label="裁床单备注" prop="count">
      <el-input v-model="textarea1" style="width: 400px" :rows="2" type="textarea" />
    </el-form-item>

    <el-form-item label="裁床任务明细备注" prop="detail">
      <el-input v-model="textarea2" style="width: 400px" :rows="2" type="textarea" />
    </el-form-item>

    <el-form-item>
      <div style="margin-right: 10px">Ps.点击颜色即可快速添加</div>
      <el-button @click="onColor" type="primary" plain>
        混合色
      </el-button>
    </el-form-item>

    <el-form-item>
      <div style="margin-right: 10px">尺码</div>
      <el-button v-for="size in size" :key="size" @click="onResize(size)">
        {{ size }}
      </el-button>
    </el-form-item>

    <el-form-item>
      <span>初始排序值</span>
      <el-input type="number" v-model.number="initialSortValue" style="width: 80px; margin-left: 20px" />

      <el-checkbox v-model="customSort" style="margin-left: 20px">
        自定义排序
      </el-checkbox>

      <span style="margin-left: 40px; margin-right: 20px">排序方式</span>
      <el-select v-model="sortType" placeholder="选择排序方式" style="width: 240px">
        <el-option label="横向排序" value="horizontal" />
        <el-option label="纵向排序" value="vertical" />
      </el-select>
    </el-form-item>

    <el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%"
      @selection-change="handleSelectionChange" stripe show-summary :summary-method="getSummaries" v-if="tableVisible">
      <el-table-column label="序号" width="60">
        <template #default="{ row }">
          {{ row.sortNumber }}
        </template>
      </el-table-column>

      <el-table-column label="颜色" width="100">
        <template #default>混合色</template>
      </el-table-column>

      <el-table-column v-for="size in sizes" :key="size" :label="`扎号-${size}`" :property="size">
        <template #default="{ row }">
          <el-input type="number" v-model.number="row[size][0]" class="table-input"
            @change="(val) => handleValueChange(row, size, 0, val)" />-
          <el-input type="number" v-model.number="row[size][1]" class="table-input"
            @change="(val) => handleValueChange(row, size, 1, val)" />
        </template>
      </el-table-column>

      <el-table-column label="合计" width="100">
        <template #default="{ row }">
          {{ calculateRowTotal(row) }}
        </template>
      </el-table-column>

      <el-table-column type="selection" width="55" />
      <el-table-column label="纵向复制" width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click.prevent="deleteRow(scope.$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 合计行 -->
    <!-- <div style="margin-top: 20px; background-color: #f2f2f2; padding: 10px">
          <span style="margin-right: 20px">合计</span>
          <span v-for="size in sizes" :key="size" style="margin-right: 20px">
              {{ calculateColumnTotal(size) }}
          </span>
          <span>{{ calculateGrandTotal() }}</span>
      </div> -->
  </el-form>
</template>

<script setup>
import { reactive, ref, watch } from "vue";

// 数据部分保持不变
const textarea1 = ref('');
const textarea2 = ref('');
const formSize = ref("default");
const ruleForm = reactive({ name: "" });
const sortType = ref("horizontal");
const size = ref(["S", "M", "L", "XL"]);
const sizes = ref(["S", "M", "L", "XL"]);
const tableData = ref([]);
const tableVisible = ref(false);
const multipleSelection = ref([]);
const nextId = ref(1);
const initialSortValue = ref(1);
const customSort = ref(false);

const rules = reactive({
  name: [{ required: true, message: "请输入床次", trigger: "blur" }],
});

// 添加汇总方法
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }

    if (index === 1) { // 颜色列
      sums[index] = "";
      return;
    }

    if (column.property) { // 动态尺码列
      sums[index] = data.reduce((sum, row) => {
        const [val1 = 0, val2 = 0] = row[column.property] || [];
        return sum + val1 + val2;
      }, 0);
    }

    if (index === columns.length - 3) { // 合计列
      sums[index] = data.reduce((total, row) => {
        return total + calculateRowTotal(row);
      }, 0);
    }
  });
  return sums;
};

// 计算方法
const calculateRowTotal = (row) => {
  return sizes.value.reduce((total, size) => {
    const [val1 = 0, val2 = 0] = row[size] || [];
    return total + val1 + val2;
  }, 0);
};

// 添加行方法（保持响应式）
const onColor = () => {
  tableVisible.value = true;
  const newRow = sizes.value.reduce((acc, size) => {
    acc[size] = reactive([0, 0]);
    return acc;
  }, {});
  newRow.id = nextId.value; // 添加ID属性
  // 动态计算新行的排序号
  newRow.sortNumber = initialSortValue.value + tableData.value.length;
  nextId.value += 1; // ID加1
  tableData.value.push(reactive(newRow));
};

watch(initialSortValue, (newVal) => {
  if (!customSort.value) { // 仅在非自定义排序模式下更新
    tableData.value.forEach((row, index) => {
      row.sortNumber = newVal + index;
    });
  }
});

const onResize = (size) => {
  sizes.value.push(size);
  console.log(`Selected size: ${size}`);
};

const deleteRow = (index) => {
  tableData.value.splice(index, 1)
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

// 值变化处理函数
const handleValueChange = (currentRow, size, index, value) => {
  // Update all values in the current row
  sizes.value.forEach(s => {
    currentRow[s] = [value, value];
  });

  // If row is selected, update all selected rows
  if (multipleSelection.value.includes(currentRow)) {
    multipleSelection.value.forEach(row => {
      if (row !== currentRow) {
        sizes.value.forEach(s => {
          row[s] = [value, value];
        });
      }
    });
  }

  // Keep keys ordered according to sizes
  const orderedRow = {};
  sizes.value.forEach(s => {
    orderedRow[s] = currentRow[s];
  });
  Object.assign(currentRow, orderedRow);
};

// const selectable = (row) => {
//   ![1].includes(row)
//   console.log(row)
// }

</script>

<style scoped>
.table-input {
  width: 60px;
  margin: 0 5px;
}

/* 确保合计行样式 */
.el-table__footer .cell {
  font-weight: bold;
  background-color: #f2f2f2;
}
</style>
